import logging

from flask import jsonify, request

from iHome import redis_store, db, constants
from iHome.api_1_0 import api
from iHome.models import Area, House, Facility, HouseImage
from iHome.utils import qiniu_key
from iHome.utils.image import storage

"""
查询地区信息
接口：/areas/    get
响应  需要data
"""


@api.route('/areas/', methods=['GET'])
def get_area():
    redis_key = 'areas_list'
    redis_data = redis_store.get(redis_key)

    """判断数据有值直接返回 return"""
    if redis_data:
        return jsonify(errno='0', errmsg='地区信息查询成功！', data=eval(redis_data))

    """缓存失效了"""
    areas = Area.query.all()
    """列表推导式"""
    areas_list = [a.to_dict() for a in areas]

    """把数据存到缓存里面"""
    redis_store.setex(redis_key, 3600, str(areas_list))

    return jsonify(errno='0', errmsg='地区信息查询成功！', data=areas_list)


"""发布新房源"""
"""
接口  /houses/   post 
前端发送过来的json数据
    {
        "title":"",
        "price":"",
        "area_id":"1",
        "address":"",
        "room_count":"",
        "acreage":"",
        "unit":"",
        "capacity":"",
        "beds":"",
        "deposit":"",
        "min_days":"",
        "max_days":"",
        "facility":["7","8"]
    }
响应： errno 0
    errmsg 成功
    data:{
        'house_id':'house.id'
    }
"""
@api.route('/houses/', methods=['POST'])
# @login_required
def commit_house():

    p = dict(request.json)

    title = p.get('title')
    price = p.get('price')
    area_id = p.get('area_id')
    address = p.get('address')
    room_count = p.get('room_count')
    acreage = p.get('acreage')
    unit = p.get('unit')
    capacity = p.get('capacity')
    beds = p.get('beds')
    deposit = p.get('deposit')
    min_days = p.get('min_days')
    max_days = p.get('max_days')
    facility = p.get('facility')

    user_id = 1

    if not all(
            [title, price, address, area_id, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days]):
        return jsonify(errno='4001', errmsg='参数缺失')

    try:
        price = int(float(price) * 100)
        deposit = int(float(deposit) * 100)
    except Exception as e:
        logging.error(e)
        return jsonify(errno='4001', errmsg='价格必须是数字')

    house = House()
    house.user_id = user_id
    house.area_id = area_id
    house.title = title
    house.price = price
    house.address = address
    house.room_count = room_count
    house.acreage = acreage
    house.unit = unit
    house.capacity = capacity
    house.beds = beds
    house.deposit = deposit
    house.min_days = min_days
    house.max_days = max_days

    facility = Facility.query.filter(Facility.id.in_(facility)).all()
    house.facilities = facility

    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        db.session.rollback()
        return jsonify(errno='4001', errmsg='保存房屋信息失败')

    return jsonify(errno='0', errmsg='发布新房源成功',data={'house_id': house.id})


@api.route('/houses/<int:house_id>/images/', methods=['POST'])
# @login_required
def upload_images(house_id):
    """
    上传房源图片
    1.取到客户端上传的文件,并判断
    2.使用七牛上传文件
    3.更新当前用户头像地址信息
    4.返回用户头像地址
    :return:
    """

    # 1.取到客户端上传的文件,并判断

    user_id = 1
    try:
        image_file = request.files["house_image"]
        house_data = image_file.read()
    except Exception as e:
        # current_app.logger.error(e)
        return jsonify(errno='4001', errmsg="传入参数有误")

    """获取image_filer的名字"""
    print(image_file.filename)

    try:
        house = House.query.filter_by(id=house_id).first()
    except Exception as e:
        return jsonify(errno='4001', errmsg='房屋不存在')

    # 2.使用七牛上传文件
    try:
        image_name = storage(house_data, image_file.filename)
    except Exception as e:
        return jsonify(errno='4001', errmsg='上传图片失败')

    try:
        house.index_image_url = image_name
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify(errno='4101', errmsg='图片保存失败')

    """添加到图片表"""

    house_img = HouseImage(house_id=house_id, url=image_name)
    db.session.add(house_img)
    db.session.commit()

    # 4.返回房屋图片地址
    house_url = constants.QINIU_DOMIN_PREFIX + image_name
    return jsonify(errno='0', errmsg='图片上传成功', data={"url": house_url})


@api.route('/houses/<int:house_id>/', methods=['GET'])
# @login_required
def load_house_detail(house_id):
    if house_id <= 0:
        return jsonify(errno='4002', errmsg='房屋ID错误')

    """获取当前登录用户id"""
    user_id = 2

    """根据房屋id获取房屋详情"""
    house = House.query.filter_by(id=house_id).first()
    house_data = house.to_full_dict()

    """缓存:先获取是否有缓存"""
    try:
        redis_house_key = 'house_data_' + str(house_id)
        redis_data = redis_store.get(redis_house_key)
    except Exception as e:
        return jsonify(errno='4001', errmsg='数据库操作失败')
    """判断数据有值直接返回 return"""
    if redis_data:
        return jsonify(errno='0', errmsg='房屋详情查询成功！', data={'user_id': user_id, 'house': eval(redis_data)})

    """把数据存到缓存里面"""
    redis_store.setex(redis_house_key, 3600, str(house_data))

    return jsonify(errno=0, errmsg='房屋详情', data={'user_id': user_id, 'house': house_data})


"""
主页轮播图获取
/houses/index/
GET
查找到所有房屋，找到其中卖的最多的房子的前五条
返回查找到的图片
"""
@api.route('/houses/index/', methods=['GET'])
def house_index():
    house = House.query.order_by(House.order_count.desc()).limit(5).all()
    house_list = []
    for i in house:
        house_list.append({
            'house_id': i.id,
            'img_url': constants.QINIU_DOMIN_PREFIX + i.index_image_url,
            'title': i.title,
        })
    # print('数据为：' + str(house_list))

    redis_key = 'house_index_images'

    try:
        redis_index_data = redis_store.get(redis_key)
    except Exception as e:
        return jsonify(errno='4001', errmsg='数据库获取失败')

    if redis_index_data:
        return jsonify(errno='0', errmsg='OK', data=eval(redis_index_data))

    redis_store.setex(redis_key, 3600, str(house_list))

    return jsonify(errno='0', errmsg='OK', data=house_list)



















